//
//  AccountBoundViewController.m
//  PigMarket
//
//  Created by mac on 2019/4/15.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AccountBoundViewController.h"
#import "SystemSetingCell.h"
#import "PhoneViewController.h"

#define kBind @"绑定"
#define kUnbind @"解绑"

@interface AccountBoundViewController ()


/**
 dataArr
 */
@property (nonatomic , strong) NSArray *dataArr;
/**
 phone ***
 */
@property (nonatomic , strong) NSString *replacePhoneStr;
/**
 account phone
 */
@property (nonatomic , strong) NSString *phone;
/**
 wechatUid
 */
@property (nonatomic , strong) NSString *wechatUid;
/**
 sinaUid
 */
@property (nonatomic , strong) NSString *sinaUid;
/**
 qqUid
 */
@property (nonatomic , strong) NSString *qqUid;
/**
 bindOrUnbind
 */
@property (nonatomic , strong) NSString *bindOrUnbind;
/**
 uid
 */
@property (nonatomic , strong) NSString *uid;
/**
 withdrawOpenId
 */
@property (nonatomic , strong) NSString *withdrawOpenId;
/**
 UMSocialPlatformType
 */
@property (nonatomic , assign) UMSocialPlatformType umSocialPlatformType;


@end

@implementation AccountBoundViewController

#pragma mark - view life cycle

- (void)setupUI{
    
    self.baseNavView.navTitleLabel.text = @"账号绑定";
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.rowHeight = 54.f;
}


- (void)setupLayout
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(TJ_NavBarHeight);
        make.right.left.bottom.mas_equalTo(self.view);
    }];
}


- (void)initData {
    self.phone = [UserInfoDataProvider sharedInstance].userInfo.phone;
    self.replacePhoneStr = [self.phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    NSString *detailPhone = [NSString stringWithFormat:@"%@更改",self.replacePhoneStr];
    
    self.wechatUid = [UserInfoDataProvider sharedInstance].userInfo.wxOpenid;
    self.sinaUid = [UserInfoDataProvider sharedInstance].userInfo.wbOpenid;
    self.qqUid = [UserInfoDataProvider sharedInstance].userInfo.qqOpenid;
    
    self.dataArr = @[@[@{@"title":@"手机号绑定",@"detail":detailPhone}],
                     @[@{@"title":@"微信绑定",@"detail":[JTool iSNull:self.wechatUid] ? kBind : kUnbind},
                       @{@"title":@"QQ绑定",@"detail":[JTool iSNull:self.qqUid] ? kBind : kUnbind},
                       @{@"title":@"微博绑定",@"detail":[JTool iSNull:self.sinaUid] ? kBind : kUnbind}]];
    
    [self.tableView reloadData];
}


#pragma mark - delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArr[section] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SystemSetingCell *cell = [SystemSetingCell cellWithTableView:tableView];
    cell.infoDic = self.dataArr[indexPath.section][indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {//手机号更改
        NSString *message = [NSString stringWithFormat:@"您目前绑定手机号为%@,确定要修改此绑定号码吗?",self.replacePhoneStr];
        
        @weakify(self);
        [self showMyAlertWithTitle:nil message:message confirmBtnTitle:@"修改号码" callBack:^{
            @strongify(self);
            PhoneViewController *phoneVC = [[PhoneViewController alloc] init];
            phoneVC.tipsTitle = BindNewPhoneNumber;
            [self.navigationController pushViewController:phoneVC animated:YES];
        }];
        
    } else {
        NSDictionary *dic = self.dataArr[indexPath.section][indexPath.row];
        self.bindOrUnbind = dic[@"detail"];
        NSString *message = [NSString stringWithFormat:@"是否%@",self.bindOrUnbind];
        
        @weakify(self);
        [self showMyAlertWithTitle:@"提示" message:message confirmBtnTitle:self.bindOrUnbind callBack:^{
            @strongify(self);
            switch (indexPath.row) {
                case 0:
                {
                    self.umSocialPlatformType = UMSocialPlatformType_WechatSession;
                }
                    break;
                case 1:
                {
                    self.umSocialPlatformType = UMSocialPlatformType_QQ;
                    
                }
                    break;
                case 2:
                {
                    self.umSocialPlatformType = UMSocialPlatformType_Sina;
                    
                }
                    break;
                default:
                    break;
            }
            
            //解绑 绑定sdk
            [self changeBindPlatform];
        }];
    }
}


#pragma mark - private method
- (void)refreshData {
    [self initData];
    [self.tableView reloadData];
}


- (void)changeBindPlatform{
   
    if ([self.bindOrUnbind isEqualToString:kBind]) {//绑定
        @weakify(self);
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:self.umSocialPlatformType currentViewController:nil completion:^(id result, NSError *error) {
            @strongify(self);
            UMSocialUserInfoResponse *resp = result;
            //绑定是 保存openid 提现z操作时用到
            self.withdrawOpenId = resp.openid;
            
            //授权登录用uid
            self.uid = resp.uid;
            PMLog(@"%@",self.uid);

            //绑定借口请求
            [self changeBindRequest];
            
        }];
    } else if ([self.bindOrUnbind isEqualToString:kUnbind]) {//解绑
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [[UMSocialManager defaultManager] cancelAuthWithPlatform:self.umSocialPlatformType completion:^(id result, NSError *error) {
                
                self.uid = nil;
                //解绑借口请求
                [self changeBindRequest];
            }];
        });
    }
}


//绑定 解绑借口请求
- (void)changeBindRequest{
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
   
    AccountBindParam *param = [[AccountBindParam alloc] init];
    param.memberId = memberId;
    param.account = self.uid;
    param.openId = self.withdrawOpenId;
    switch (self.umSocialPlatformType) {
        case UMSocialPlatformType_QQ:
            param.type = @2;
            break;
        case UMSocialPlatformType_WechatSession:
            param.type = @1;
            break;
        case UMSocialPlatformType_Sina:
            param.type = @4;
            break;
        default:
            param.type = @5;
            break;
    }
    
    if ([self.bindOrUnbind isEqualToString:kBind]) {//绑定
        param.isBind = @1;
    } else if ([self.bindOrUnbind isEqualToString:kUnbind]) {//解绑
        param.isBind = @0;
    }
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] accountBindOrUnbindWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self toastWithContent:[NSString stringWithFormat:@"%@成功",self.bindOrUnbind]];
      
        
        //更新缓存数据
        UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;

        switch (self.umSocialPlatformType) {
            case UMSocialPlatformType_QQ:
                self.qqUid = self.uid;
                break;
            case UMSocialPlatformType_WechatSession:
                self.wechatUid = self.uid;
  
                break;
            case UMSocialPlatformType_Sina:
                self.sinaUid = self.uid;
                break;
            default:
                break;
        }
        userInfo.qqOpenid = self.qqUid;
        userInfo.wbOpenid = self.sinaUid;
        userInfo.wxOpenid = self.wechatUid;
        userInfo.withdrawWx = self.withdrawOpenId;
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        PMLog(@"%@",userInfo.wxOpenid);
        [self refreshData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


#pragma mark - getter and setter

- (NSArray *)dataArr {
    
    if (!_dataArr) {
        _dataArr = [[NSArray alloc] init];
    }
    return _dataArr;
}

- (void)registerTableViewCell{
    
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
}



- (void)addNotifications
{
    [kNotificationCenter addObserver:self selector:@selector(refreshData) name:NotificationPhoneChanged object:nil];
}


-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
